﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using FastReflectionLib;
using Newtonsoft.Json;
using System.Data;
using Senparc.Weixin.QY.Entities;
using System.Net;
using System.IO;
using QJY.Data;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Text.RegularExpressions;
using QJY.Common;
using System.Configuration;


namespace QJY.API
{
    /// <summary>
    /// 第三方接口
    /// </summary>
    public class OUTManage : IWsService
    {
        public void ProcessRequest(HttpContext context, ref Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            MethodInfo methodInfo = typeof(OUTManage).GetMethod(msg.Action.ToUpper());
            OUTManage model = new OUTManage();
            methodInfo.FastInvoke(model, new object[] { context, msg, P1, P2, UserInfo });
        }

        public void SQL(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            if (P1 == "get")
            {
                msg.Result = new JH_Auth_CommonB().GetDTByCommand(P2);
            }
            else
            {
                new JH_Auth_CommonB().ExsSql(P2);
            }

        }
        #region  工作日志
        /// <summary>
        /// 获取工作任务接口
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void GETTASKBYUDS(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            IDictionary<string, string> parameters = GetParamFromContext(context, UserInfo.User.UserName);

            string result = CommonHelp.GetHttpResponse(GetAPI("/pm/api/getTaskByUDS"), parameters, "GET");
            msg.Result = result;

            //msg.Result = "[{\"taskId\":\"IT_MD02043944\",\"progress\":0,\"status\":\"2\",\"milestoneName\":\"内部管理\",\"endedAt\":\"2018 - 12 - 31\",\"startedAt\":\"2018 - 01 - 01\",\"owner\":\"张务岩\",\"projectId\":\"IT_MD02043850\",\"taskName\":\"外包合同管理1\",\"projectName\":\"综合管理部内部管理 - 2018\",\"milestoneId\":\"IT_MD02043867\"},{\"taskId\":\"IT_MD02043944\",\"progress\":0,\"status\":\"2\",\"milestoneName\":\"内部管理\",\"endedAt\":\"2018 - 12 - 31\",\"startedAt\":\"2018 - 01 - 01\",\"owner\":\"张务岩\",\"projectId\":\"IT_MD02043850\",\"taskName\":\"外包合同管理2\",\"projectName\":\"综合管理部内部管理 - 2018\",\"milestoneId\":\"IT_MD02043867\"}]";
        }

        /// <summary>
        /// 我的工作日志接口
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void GETMYLOGBYUDS(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {

            IDictionary<string, string> parameters = GetParamFromContext(context, UserInfo.User.UserName);

            string result = CommonHelp.GetHttpResponse(GetAPI("/pm/api/getMyLogByUDS"), parameters, "GET");
            msg.Result = result;

            //msg.Result = "[{\"work_date\":\"2018-07-10\",\"taskId\":\"IT_MD02043959\",\"overworkHours\":0,\"logId\":\"11305f86f6a549e38c85af3703051736\",\"billingHoursDesc\":\"项目经理工作日志，提报到部门负责人处。\",\"billingHours\":0,\"overworkHoursDesc\":\"外部资料报送\",\"taskName\":\"外部资料报送\",\"logStatus\":1,\"milestoneName\":\"内部管理\",\"userId\":\"yuhui\",\"userName\":\"于辉\",\"projectName\":\"综合管理部内部管理 - 2018\"},{\"work_date\":\"2018-07-10\",\"taskId\":\"IT_MD02043956\",\"overworkHours\":0,\"logId\":\"825b493c23d345e4a9d8a5ee9f25b6de\",\"billingHoursDesc\":\"非立项项目，有资源经理的测试。\",\"billingHours\":7.5,\"overworkHoursDesc\":\"\",\"taskName\":\"部门会议\",\"logStatus\":1,\"milestoneName\":\"内部管理\",\"userId\":\"yuhui\",\"userName\":\"于辉\",\"projectName\":\"综合管理部内部管理 - 2018\"},{\"work_date\":\"2018-07-09\",\"taskId\":\"IT_MD02049415\",\"overworkHours\":0,\"logId\":\"6879b32d154e4a4bbc742b4d8f58e9d3\",\"billingHoursDesc\":\"非立项项目，项目经理工作日志，由资源所在部门负责人审批。\",\"billingHours\":0,\"overworkHoursDesc\":\"\",\"taskName\":\"0699 - 安全管理 - 其他工作\",\"logStatus\":1,\"milestoneName\":\"06 - 安全管理组2018运维工作\",\"userId\":\"yuhui\",\"userName\":\"于辉\",\"projectName\":\"生产与营运运维部2018年内部管理\"},{\"work_date\":\"2018-07-06\",\"taskId\":\"IT_MD02049415\",\"overworkHours\":0,\"logId\":\"6879b32d154e4a4bbc742b4d8f58e9d3\",\"billingHoursDesc\":\"非立项项目，项目经理工作日志，由资源所在部门负责人审批。\",\"billingHours\":0,\"overworkHoursDesc\":\"\",\"taskName\":\"0699 - 安全管理 - 其他工作\",\"logStatus\":1,\"milestoneName\":\"06 - 安全管理组2018运维工作\",\"userId\":\"yuhui\",\"userName\":\"于辉\",\"projectName\":\"生产与营运运维部2018年内部管理\"}]";
        }

        //根据ID获取日志详细信息接口
        public void GETLOGDETAILBYIDS(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {

            IDictionary<string, string> parameters = GetParamFromContext(context, UserInfo.User.UserName);

            string result = CommonHelp.GetHttpResponse(GetAPI("/pm/api/getLogDetailByIds"), parameters, "GET");
            msg.Result = result;

        }

        /// <summary>
        /// 我的待审批工作日志接口
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void GETMYAPPROVELOGBYUDS(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            IDictionary<string, string> parameters = GetParamFromContext(context, UserInfo.User.UserName);

            string result = CommonHelp.GetHttpResponse(GetAPI("/pm/api/getMyApproveLogByUDS"), parameters, "GET");
            msg.Result = result;

            //msg.Result = "[{\"taskId\":\"28a382ddcf5440fabc490a76855ec7f6\",\"overworkHours\":0,\"logId\":\"a5f3a40d720f4df0bbb94e25144f9c7e\",\"billingHoursDesc\":\"\",\"billingHours\":7,\"overworkHoursDesc\":\"\",\"taskName\":\"压力测试任务1\",\"logStatus\":1,\"milestoneName\":\"性能测试\",\"userId\":\"zhangwy\",\"userName\":\"张务岩\",\"projectName\":\"压力测试使用数据\"},{\"taskId\":\"28a382ddcf5440fabc490a76855ec7f6\",\"overworkHours\":0,\"logId\":\"619cebd1dd6b4c5caa7b43269c4f9da1\",\"billingHoursDesc\":\"\",\"billingHours\":7,\"overworkHoursDesc\":\"\",\"taskName\":\"压力测试任务1\",\"logStatus\":1,\"milestoneName\":\"性能测试\",\"userId\":\"zhangwy\",\"userName\":\"张务岩\",\"projectName\":\"压力测试使用数据\"},{\"taskId\":\"28a382ddcf5440fabc490a76855ec7f6\",\"overworkHours\":0,\"logId\":\"9fb82efb55ce4fd9a5fbc83b14a47c82\",\"billingHoursDesc\":\"\",\"billingHours\":7,\"overworkHoursDesc\":\"\",\"taskName\":\"压力测试任务1\",\"logStatus\":1,\"milestoneName\":\"性能测试\",\"userId\":\"zhangwy\",\"userName\":\"张务岩\",\"projectName\":\"压力测试使用数据\"},{\"taskId\":\"IT_MD02043959\",\"overworkHours\":0,\"logId\":\"11305f86f6a549e38c85af3703051736\",\"billingHoursDesc\":\"项目经理工作日志，提报到部门负责人处。\",\"billingHours\":0,\"overworkHoursDesc\":\"\",\"taskName\":\"外部资料报送\",\"logStatus\":1,\"milestoneName\":\"内部管理\",\"userId\":\"yuhui\",\"userName\":\"于辉\",\"projectName\":\"综合管理部内部管理 - 2018\"},{\"taskId\":\"IT_MD02049415\",\"overworkHours\":0,\"logId\":\"6879b32d154e4a4bbc742b4d8f58e9d3\",\"billingHoursDesc\":\"非立项项目，项目经理工作日志，由资源所在部门负责人审批。\",\"billingHours\":0,\"overworkHoursDesc\":\"\",\"taskName\":\"0699 - 安全管理 - 其他工作\",\"logStatus\":1,\"milestoneName\":\"06 - 安全管理组2018运维工作\",\"userId\":\"yuhui\",\"userName\":\"于辉\",\"projectName\":\"生产与营运运维部2018年内部管理\"}]";
        }

        /// <summary>
        /// 审批工作日志
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void APPROVELOGBYIDS(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            IDictionary<string, string> parameters = GetParamFromContext(context, UserInfo.User.UserName);

            string result = CommonHelp.GetHttpResponse(GetAPI("/pm/api/approveLogByIds "), parameters, "POST");
            if (result.Trim().ToLower() != "success")
            {
                msg.ErrorMsg = result.Trim();
            }
        }

        /// <summary>
        /// 提交工作日志
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void SUBMITLOG(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            int GZRZ_DAYS = Int32.Parse(ConfigurationManager.AppSettings["GZRZ_DAYS"]);
            string workDate = context.Request["workDate"];
            string billinghoursdesc = context.Request["billinghoursdesc"];
            string overworkhoursdesc = context.Request["overworkhoursdesc"];

            if (string.IsNullOrEmpty(workDate))
            {
                msg.ErrorMsg = "请选择日志时间";
                return;
            }
            DateTime wkDate = DateTime.Parse(workDate);
            if (wkDate > DateTime.Now)
            {
                msg.ErrorMsg = "不能填写未来的工作日志";
                return;
            }

            if (DateTime.Parse(workDate) < DateTime.Now.AddDays(-GZRZ_DAYS))
            {
                msg.ErrorMsg = "只能补" + GZRZ_DAYS + "天内的日志";
                return;
            }

            if ((!string.IsNullOrEmpty(billinghoursdesc) && billinghoursdesc.Length > 300) || (!string.IsNullOrEmpty(overworkhoursdesc) && overworkhoursdesc.Length > 300))
            {
                msg.ErrorMsg = "日志内容不能超过300个字";
                return;
            }



            IDictionary<string, string> parameters = GetParamFromContext(context, UserInfo.User.UserName);

            string result = CommonHelp.GetHttpResponse(GetAPI("/pm/api/submitLog"), parameters, "POST");
            if (result.Trim().ToLower() != "success")
            {
                msg.ErrorMsg = result.Trim();
            }

        }

        public void GETHOLIDAYS(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            IDictionary<string, string> parameters = GetParamFromContext(context, UserInfo.User.UserName);
            string result = CommonHelp.GetHttpResponse(GetAPI("/pm/api/getHolidays"), parameters, "GET");

            msg.Result = result;

            //msg.Result = "[{\"reDate\":\"2018-02-15\",\"status\":\"1\"},{\"reDate\":\"2018-02-17\",\"status\":\"1\"},{\"reDate\":\"2018-04-08\",\"status\":\"2\"},{\"reDate\":\"2018-04-30\",\"status\":\"1\"},{\"reDate\":\"2018-09-29\",\"status\":\"2\"},{\"reDate\":\"2018-09-30\",\"status\":\"2\"},{\"reDate\":\"2018-02-20\",\"status\":\"1\"},{\"reDate\":\"2018-02-21\",\"status\":\"1\"},{\"reDate\":\"2018-04-05\",\"status\":\"1\"},{\"reDate\":\"2018-05-01\",\"status\":\"1\"},{\"reDate\":\"2018-10-02\",\"status\":\"1\"},{\"reDate\":\"2018-10-03\",\"status\":\"1\"},{\"reDate\":\"2018-01-01\",\"status\":\"1\"},{\"reDate\":\"2018-02-18\",\"status\":\"1\"},{\"reDate\":\"2018-02-19\",\"status\":\"1\"},{\"reDate\":\"2018-02-24\",\"status\":\"2\"},{\"reDate\":\"2018-04-28\",\"status\":\"2\"},{\"reDate\":\"2018-10-01\",\"status\":\"1\"},{\"reDate\":\"2018-10-05\",\"status\":\"1\"},{\"reDate\":\"2018-02-11\",\"status\":\"2\"},{\"reDate\":\"2018-02-16\",\"status\":\"1\"},{\"reDate\":\"2018-04-06\",\"status\":\"1\"},{\"reDate\":\"2018-06-18\",\"status\":\"1\"},{\"reDate\":\"2018-09-24\",\"status\":\"1\"},{\"reDate\":\"2018-10-04\",\"status\":\"1\"}]";
        }

        //审批数量
        public void GETMYAPPROVELOGCOUNT(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            IDictionary<string, string> parameters = GetParamFromContext(context, UserInfo.User.UserName);
            string result = CommonHelp.GetHttpResponse(GetAPI("/pm/api/getMyApproveLogCount"), parameters, "GET");
            msg.Result = result;

        }

        //任务查询日志
        public void GETLOGDETAILBYUDT(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            IDictionary<string, string> parameters = GetParamFromContext(context, UserInfo.User.UserName);
            string result = CommonHelp.GetHttpResponse(GetAPI("/pm/api/getLogDetailByUDT"), parameters, "GET");
            msg.Result = result;

        }

        //获取工时配置
        public void GETWORKCONFIG(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            string hours = "7.5";
            var GZRZ_WORK = ConfigurationManager.AppSettings["GZRZ_WORK"];
            if (GZRZ_WORK != null)
            {
                hours = GZRZ_WORK;
            }

            msg.Result = hours;
        }
        #endregion


        public IDictionary<string, string> GetParamFromContext(HttpContext context, string UserName, string httpmethod = "POST")
        {
            IDictionary<string, string> parameters = new Dictionary<string, string>();
            var paramss = httpmethod == "GET" ? context.Request.QueryString : context.Request.Form;
            foreach (string v in paramss.Keys)
            {
                if (v.ToLower() != "action" && v.ToLower() != "szhlcode")
                {
                    parameters.Add(v, Common.StringHelper.StripSQLInjection(paramss[v].ToString()));
                }
            }

            if (!parameters.ContainsKey("userId"))
            {
                parameters.Add("userId", GetYUserByWXUser(UserName));
            }
            if (parameters.ContainsKey("sign"))
            {
                parameters.Remove("sign");
            }
            var sign = Security.EncryptDES(ArrayReverse(DateTime.Now.ToString("yyyyMMddHHmmss")));
            parameters.Add("sign", sign);
            return parameters;
        }

        public string GetAPI(string apiName)
        {
            var host = ConfigurationManager.AppSettings["GZRZ_API"];
            if (host.EndsWith("/"))
            {
                host = host.TrimEnd('/');
            }

            return host + apiName;
        }

        //字符串反转
        public string ArrayReverse(string text)
        {
            char[] charArray = text.ToCharArray();
            Array.Reverse(charArray);

            return new string(charArray);
        }


        /// <summary>
        /// 根据当前用户名获取域用户名
        /// </summary>
        /// <param name="UserName"></param>
        /// <returns></returns>
        public string GetYUserByWXUser(string UserName)
        {
            string WXUser = UserName;
            try
            {
                DataTable dtUser = new JH_Auth_UserB().GetDTByCommand("SELECT UserName  from  WeChatSign.dbo.AD WHERE WeChatUserName='" + UserName + "' ");
                if (dtUser.Rows.Count > 0)
                {
                    WXUser = dtUser.Rows[0]["UserName"].ToString();
                }
            }
            catch (Exception ex) {
            }
            return WXUser;


        }

        //转换域账号
        public string GetWXUserByYUser(string UserName)
        {
            string WXUser = UserName;
            try
            {
                DataTable dtUser = new JH_Auth_UserB().GetDTByCommand("SELECT  WeChatUserName   from  WeChatSign.dbo.AD WHERE UserName='" + UserName + "' ");
                if (dtUser.Rows.Count > 0)
                {
                    WXUser = dtUser.Rows[0]["WeChatUserName"].ToString();
                }
            }
            catch (Exception ex) { }
            return WXUser;


        }
        public void SENDRTX(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            string strTitle = System.Web.HttpUtility.UrlEncode(P1, System.Text.Encoding.GetEncoding("GB2312"));
            string strMsg = System.Web.HttpUtility.UrlEncode(P2, System.Text.Encoding.GetEncoding("GB2312"));

            SendRtxMsg(strTitle, strMsg, "ZhaoGuiJin");
        }

        //发送RTX消息
        public void SendRtxMsg(string title, string msg, string receivers, string okurl = "")
        {
            string RTXIP = System.Configuration.ConfigurationManager.AppSettings["RTXIP"].ToString();

            string wereceivers = "";
            //转换域账号
            DataTable dtUser = new JH_Auth_UserB().GetDTByCommand("SELECT  UserName    from  WeChatSign.dbo.AD WHERE  WeChatUserName in ('" + receivers.ToFormatLike(',') + "')");
            if (dtUser.Rows.Count > 0)
            {
                foreach (DataRow dr in dtUser.Rows)
                {
                    if (wereceivers == "")
                    {
                        wereceivers = dr["UserName"].ToString();
                    }
                    else
                    {
                        wereceivers += "," + dr["UserName"].ToString();
                    }

                }
            }

            string url = RTXIP + "/sendnotify.cgi?title=" + title + "&receiver=" + wereceivers;
            if (msg != "")
            {
                url += "&msg=" + msg;
            }
            if (okurl != "")
            {
                url += "&okurl=" + okurl;
            }

            CommonHelp.GetHttpResponse(url, null, "GET");

        }



    }


}